﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;

namespace BizElements.Generator
{
    public partial class AssemblyPickerCtl : UserControl
    {
        // Assemblies are loaded only once per session.
        Dictionary<string, Assembly> loadedAssemblies = new Dictionary<string, Assembly>();

        public AssemblyPickerCtl()
        {
            InitializeComponent();
        }

        #region Open file and load assembly.

        private void uiAsmOpenDialog_Click(object sender, EventArgs e)
        {
            var answer = this.uiAsmFileDialog.ShowDialog();
            if (answer == DialogResult.OK)
            {
                this.uiAsmPath.Text = this.uiAsmFileDialog.FileName;              
            }
        }        

        private bool LoadAndCacheAssembly(string filePath)
        {
            bool alreadyLoaded = this.loadedAssemblies.ContainsKey(filePath);
            if (alreadyLoaded)
                return true;

            this.loadedAssemblies[filePath] = ReflectionUtil.LoadAssembly(filePath);
            return true;
        }

        #endregion

        #region Properties and events.

        [Browsable(false)]
        public string AssemblyPath
        {
            get { return this.uiAsmPath.Text; }
        }

        [Browsable(false)]
        public Assembly Assembly
        {
            get
            {
                Assembly asm;
                this.loadedAssemblies.TryGetValue(this.AssemblyPath, out asm);
                return asm;
            }
        }

        public event EventHandler AssemblySelected;

        #endregion

        public void ReadSettings(BizElementsSettings projectSettings)
        {
            this.uiAsmPath.Text = projectSettings["AssemblyPickerCtl_AsmPath"];
        }

        public void WriteSettings(BizElementsSettings projectSettings)
        {
            projectSettings["AssemblyPickerCtl_AsmPath"] = this.uiAsmPath.Text.Trim();
        }

        private void uiLoadAsm_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.uiAsmPath.Text))
            {
                MessageBox.Show(Messages.AssemblyPickerCtl_PleaseSelectAnAssembly);
                return;
            }

            bool isLoaded = LoadAndCacheAssembly(this.uiAsmPath.Text);
            if (isLoaded)
            {
                if (this.AssemblySelected != null)
                    AssemblySelected(this, new EventArgs());
            }
            else
            {
                MessageBox.Show(Messages.AssemblyPickerCtl_FileIsNotValidAssembly);
            }  
        }
    }    
}
